package com.yyks.es.dubbo.config;

import com.google.common.collect.Lists;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * @author shuai
 * @date 2019/09/27 13:15
 */
@Configuration
public class EsConfig {

    @Value("${elasticSearch.hosts}")
    private String hosts;
    @Value("${elasticSearch.port}")
    private int port;
    @Value("${elasticSearch.username}")
    private String username;
    @Value("${elasticSearch.password}")
    private String password;

    private static String schema = "http"; // 使用的协议

    private static int connectTimeOut = 1000; // 连接超时时间
    private static int socketTimeOut = 30000; // 连接超时时间
    private static int connectionRequestTimeOut = 500; // 获取连接的超时时间

    private static int maxConnectNum = 100; // 最大连接数
    private static int maxConnectPerRoute = 100; // 最大路由连接数

    @Bean
    public RestHighLevelClient restHighLevelClient() {
        //设置auth信息
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
        //集群地址
        List<HttpHost> httpHostList = Lists.newArrayList();
        String[] hostStrs = hosts.split(",");
        for (String hostStr : hostStrs) {
            httpHostList.add(new HttpHost(hostStr, port, schema));
        }
        //配置
        RestClientBuilder builder = RestClient.builder(httpHostList.toArray(new HttpHost[0]))
                // 异步httpclient连接延时配置
                .setRequestConfigCallback(requestBuilder -> {
                    requestBuilder.setConnectTimeout(connectTimeOut);
                    requestBuilder.setSocketTimeout(socketTimeOut);
                    requestBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);
                    return requestBuilder;
                })
                // 异步httpclient连接数配置
                .setHttpClientConfigCallback(httpClientBuilder -> {
                    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    httpClientBuilder.setMaxConnTotal(maxConnectNum);
                    httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);
                    return httpClientBuilder;
                });
        //创建对象
        return new RestHighLevelClient(builder);
    }

}
